package com.yanyq.message.m1;


import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;

public class ZkUtil {
    public static ZooKeeper zk = getZk();

    public static ZooKeeper getZk(){
        try {
            final String url = "127.0.0.1:2181";
            ZooKeeper zk = new ZooKeeper(url,300,new Watcher() {
                @Override
                public void process(WatchedEvent event){
                    System.out.println(">>::"+event.getType());
                }
            });
            System.out.println("zk客户端初始化完毕.....");
            return zk;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public void closeZk(ZooKeeper zk){
        try {
            if(null != zk)
                zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void operate(String path,String data,int operateType){
        if(operateType == 1){
            //create
            try {
                zk.create(path,data.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }else if(operateType == 2){
            //delete
            try {
                zk.delete(path,-1);
            } catch (InterruptedException | KeeperException e) {
                e.printStackTrace();
            }
        }else if(operateType == 3){
            //setData
            try {
                zk.setData(path, data.getBytes(),-1);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}